package com.forest.datachangetracker.context;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/****
 *
 * 数据审计数据上下文持有者(提供在业务中设置变量，审计时获取).
 *
 * @author forest
 */
public class AuditContextHolder {

    /**
     * 提供给业务设置变量
     */
    private static final ThreadLocal<Map<String,Object>> AUDIT_CONTEXT = new ThreadLocal<>();

    public static void set(String key, Object value) {
        // 获取当前线程的变量
        Map<String, Object> vars = AUDIT_CONTEXT.get();
        if(ObjectUtil.isNull(vars)) {
            vars = new ConcurrentHashMap<>();
        }
        vars.put(key, value);
        AUDIT_CONTEXT.set(vars);
    }

    public static Object get(String key) {
        // 获取当前线程的变量
        Map<String, Object> vars = AUDIT_CONTEXT.get();
        if(ObjectUtil.isNull(vars)) {
            return null;
        }
        return MapUtil.getStr(vars, key);
    }

    public static Map<String,Object> getAll() {
        return AUDIT_CONTEXT.get();
    }

    public static void clear() {
        AUDIT_CONTEXT.remove();
    }

}
